<template>
	<view class="chat">
		<u-navbar title="ai对话" :is-back="false" titleColor="#fff" :background="background"></u-navbar>
		</u-navbar>
		<scroll-view :style="{height: `${windowHeight-inputHeight - 180}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<view class="item self" v-if="item.userContent != ''">
						<view class="content right">
							<!-- <ua-markdown :source="item.userContent" :showLine="false"></ua-markdown> -->
							<zero-markdown-view :codeBgColor="themeColor" :markdown="item.userContent" />
						</view>
						<view class="avatar">
							<image :src="userImg" style="width: 100%;height: 100%;"></image>
						</view>
					</view>
					<view class="item Ai" v-if="item.botContent != ''">
						<!-- 头像 -->
						<view class="avatar">
							<image :src="artImg" style="width: 100%;height: 100%;"></image>
						</view>
						<view class="content left">
							<zero-markdown-view :markdown="item.botContent" />
							<!-- <ua-markdown :source="item.botContent" :showLine="false"></ua-markdown> -->
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
				<view class="uni-textarea">
					<textarea v-model="chatMsg" maxlength="1000" confirm-type="send" @confirm="handleSend"
						placeholder="在这里输入问题" :show-confirm-bar="false" :adjust-position="false"
						@linechange="sendHeight" @focus="focus" @blur="blur" auto-height>
						</textarea>
				</view>
				<button v-show="!requestChat" @click="handleSend" class="send-btn">发送(-2)</button>
				<button v-show="requestChat" class="sending-btn">请求中...</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				background: this.TopColor,
				codeBgColor: '##55aa7f',
				backTextColor: {
					'color': '#ffffff'
				},
				artImg: "../../static/art.jpg",
				userImg: "",
				conversationId: '', //会话的上下文id
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: '',
				requestChat: false, //是否在这请求
				//发送的消息
				chatMsg: "",
				cnnectionStatus: false,
				msgList: [{
					botContent: "",
					recordId: 0,
					titleId: 0,
					userContent: "",
					userId: 0
				}],
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight
			}
		},
		onLoad() {
			let _this = this
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = this.rpxTopx(res.height - 30)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})

			uni.showLoading({
				title: "正在召唤AI"
			})
			_this.websocketFunction()
		},
		onShow() {
			let _this = this
			setTimeout(function() {
				if (_this.cnnectionStatus) {
					uni.sendSocketMessage({
						data: 'ping',
						success: (res) => {
							return;
						},
						fail: (err) => { // 未连接打开websocket连接
							this.cnnectionStatus = false
							_this.websocketFunction()
						}
					});
				} else {
					_this.websocketFunction()
				}
			}, 500)

			this.userImg = this.$db.userInfo()['avatar'];

			let test = this.$db.get('text');
			this.msgList[0].botContent = '<p>窝窝AI为您服务：</p>' + test + '</p><p>越完整的描述，我越精确。并支持联系上下文</p>'
			this.$db.del('text')
		},
		onUnload() {
			uni.offKeyboardHeightChange()
		},
		onHide() {
			console.log('页面隐藏')
		},
		methods: {
			initHighLight() {
				hljs.configure({
					useBR: true,
					tabReplace: " ",
				});
				marked.setOptions({
					renderer: new marked.Renderer(),
					gfm: true,
					tables: true,
					breaks: false,
					pedantic: false,
					highlight: function(code, lang) {
						if (lang && hljs.getLanguage(lang)) {
							return hljs.highlight(lang, code, true).value;
						} else {
							return hljs.highlightAuto(code).value;
						}
					},
				});
			},
			back() {
				this.$common.switchTabTo('/pages/index/index');
			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height + 100)
						}
					})
				}, 25)
			},
			//发送chatGPT的聊天
			async sendToZhiShuYunChat() {
				const _this = this;
				_this.requestChat = true;
				let data = JSON.stringify({
					'question': this.chatMsg,
					'stateful': true,
					'conversation_id': this.conversationId,
					'timeout': 3000,
					'type': 1
				})
				uni.sendSocketMessage({
					data: data
				})
				this.chatMsg = '';
			},
			// 发送消息按钮
			async handleSend() {
				if (!this.$db.userInfo()) {
					this.$common.errorToShow('请先登录', () => {
						this.$common.jumpToLogin()
					})
					return
				}
				//如果消息不为空
				if (this.chatMsg != '') {
					//扣减积分并验证用户登录等情况
					let subtractScoreResult = await this.subtractScore();
					if (!subtractScoreResult) {
						return;
					}
					let sendMe = {
						botContent: "",
						recordId: this.msgList.slice(-1)[0].recordId + 1,
						titleId: 0,
						userContent: this.chatMsg,
						userId: 0
					}
					this.msgList.push(sendMe);
					let reciverChatGPT = {
						botContent: '',
						recordId: this.msgList.slice(-1)[0].recordId + 1,
						titleId: 0,
						userContent: '',
						userId: 0
					}
					this.msgList.push(reciverChatGPT);
					this.sendToZhiShuYunChat();
					this.scrollToBottom()
				} else {
					this.$common.errorToShow('不能发送空白消息!')
					return;
				}
			},
			async subtractScore() {
				//减去积分
				const updateSubtractScore = await this.$http.get("/user/updateSubtractScore", {
					'subtractScore': 2,
					'optionType': 2
				})
				const scoreRespone = await updateSubtractScore;
				console.log("scoreRespone", scoreRespone)
				if (!scoreRespone.success) {
					this.$common.errorToShow("系统错误了，等会再试吧！！！")
					return false;
				}
				return true;
			},
			//注册websocket的消息监听
			websocketFunction() {
				let _this = this
				uni.closeSocket();
				uni.onSocketClose(function(res) {
					_this.cnnectionStatus = false
					console.log('先关闭websocket', res)
				})
				if (!_this.cnnectionStatus) {
					//创建socket链接
					uni.connectSocket({
						url: _this.$http.wssDomain,
						success: function() {
							console.log('WebSocket连接成功')

						}
					})
					uni.onSocketOpen(function(res) {
						_this.requestChat = false;
						uni.hideLoading()
						_this.cnnectionStatus = true
						console.log('WebSocket连接已打开！')
					})
				}
				uni.onSocketError(function(res) {
					uni.hideLoading()
					uni.showModal({
						title: '提示',
						content: 'AI召唤失败，请退出页面重新进入',
						showCancel: false,
						success: function(res) {
							_this.$common.switchTabTo('/pages/index/index');
						}
					});
					console.log('WebSocket连接打开失败', res)
				})


				uni.onSocketMessage(function(res) {
					let context = ''
					let responseStr = res.data
					// console.log(responseStr)
					if (responseStr == 'pong') {
						console.log(responseStr)
						return
					}
					if (responseStr == "error-1") {
						//响应失败
						_this.requestChat = false;
						_this.msgList.slice(-1)[0].botContent = '哎呀！出错了!!!尝试退出页面重新尝试一下吧！'
					} else if (responseStr == "end-1") {
						//请求完成
						_this.requestChat = false;
						_this.msgList.slice(-1)[0].botContent += ""
					} else {
						let msg = JSON.parse(responseStr);
						console.log(msg)
						context = msg['delta_answer']
						_this.msgList.slice(-1)[0].botContent += context
						_this.conversationId = msg['conversation_id']
						_this.scrollToBottom();
					}
				})

			}
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #9fccff;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		height: 100vh;
		// background-color: #F6F6F6;
		background-color: #232428;

		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			// background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 18rpx 18rpx;
						margin: 0 20rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						// background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 177rpx;
			// background: #F4F5F7;
			transition: all 0.1s ease;


			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				// min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background-color: rgba(245, 250, 252, 0.8);
				transition: all 0.1s ease;
			}

			.uni-textarea {

				// padding-bottom: 70rpx;
				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 28rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 20rpx 15rpx;
					overflow: auto;
					height: auto;
				}

			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				// margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: $sendBtnbgc;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}

			.sending-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				// margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: #acacac;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
</style>